package com.wang.myblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.myblog.entity.Comment;
import com.wang.myblog.entity.dto.CommentDto;
import com.wang.myblog.mapper.CommentMapper;
import com.wang.myblog.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 博客-评论表 服务实现类
 * </p>
 *
 * @author s
 * @since 2021-05-21
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Override
    public void getTreeCommentBySid(Long sid, Page<CommentDto> page) {
        QueryWrapper<Comment> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("sid", sid);
        wrapper1.eq("pid", 0);
        wrapper1.orderByDesc("create_time");
        Page<Comment> commentPage = new Page<>(page.getCurrent(), page.getSize());
        baseMapper.selectPage(commentPage, wrapper1);
        List<CommentDto> collect = commentPage.getRecords().stream().map(item -> {
            CommentDto commentDto = new CommentDto();
            BeanUtils.copyProperties(item, commentDto);
            commentDto.setChildren(getChildren(commentDto, page.getRecords()));
            return commentDto;
        }).collect(Collectors.toList());
        page.setRecords(collect);
    }

    /**
     * 获取子菜单树
     *
     * @param root
     * @param allList
     * @return
     */
    private List<CommentDto> getChildren(CommentDto root, List<CommentDto> allList) {
        return allList.stream().map((menu) -> {
            QueryWrapper<Comment> wrapper = new QueryWrapper<>();
            wrapper.eq("pid", menu.getId());
            wrapper.orderByDesc("create_time");
            List<Comment> comments = baseMapper.selectList(wrapper);
            menu.setChildrenTotal(comments.size());
            if (comments.size() >= 6) {
                comments = comments.subList(0, 6);
            }
            for (Comment comment : comments) {
                CommentDto commentDto = new CommentDto();
                BeanUtils.copyProperties(comment, commentDto);
                return commentDto;
            }
            return null;
        }).collect(Collectors.toList());
    }
    /*private List<CommentDto> getChildren(CommentDto root, List<CommentDto> allList) {
        return allList.stream().filter((entity) -> {
            return root.getId().equals(entity.getPid());//对应关系
        }).map((menu) -> {
            List<CommentDto> children = getChildren(menu, allList);
            menu.setChildren(children);
            return menu;
        }).collect(Collectors.toList());
    }*/
}
